import { loginAPI, getUserInfoAPI } from '@/api/user.js';
import { setToken_AUTH, getToken_AUTH, setUserInfo_AUTH, getUserInfo_AUTH } from '@/utils/auth.js';

const user = {
  state: {
    token: getToken_AUTH(),
    userInfo: getUserInfo_AUTH() || {},
  },
  mutations: {
    SET_TOKEN: (state, token = '') => {
      state.token = token;
			setToken_AUTH(token);
    },
		SET_USERINFO: (state, userInfo = {}) => {
			state.userInfo = userInfo;
			setUserInfo_AUTH(userInfo);
		}
  },
  actions: {
    // 登录
		Login({ commit }) {
			return new Promise((resolve, reject) => {
				uni.login({
					success: (res) => {
						let code = res.code;
						loginAPI({
							code: code
						}).then(res => {
							if(res.data.headers.code === 0) {
								commit('SET_TOKEN', res.data.data.token);
						    commit('SET_USERINFO', res.data.data);
								resolve(res);
							}else {
								commit('SET_TOKEN', '');
                commit('SET_USERINFO', {});
							}
						}).catch(error => {
							commit('SET_TOKEN', '');
              commit('SET_USERINFO', {});
							reject(error);
						})
					},
					fail: (error) => {
						commit('SET_TOKEN', '');
            commit('SET_USERINFO', {});
						reject(error);
					}
				})
			})
		},
		// 获取用户信息
		GetUserInfo({ commit }) {
      console.log('GetUserInfo')
			return new Promise((resolve, reject) => {
				getUserInfoAPI().then(res => {
					if(res.data.headers.code === 0) {
						commit('SET_USERINFO', res.data.data);
					}else {
						commit('SET_TOKEN', '');
						commit('SET_USERINFO', {});
					}
					resolve(res);
				}).catch(error => {
					commit('SET_TOKEN', '');
					commit('SET_USERINFO', {});
					reject(error);
				})
			})
		}
	}
}

export default user
